import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 通过REST API添加TooBit定时任务
 */
public class AddScheduledTaskViaAPI {
    
    private static final String BASE_URL = "http://localhost:8080";
    
    public static void main(String[] args) {
        System.out.println("🎯 === 通过REST API添加TooBit定时任务 ===");
        System.out.println("执行时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println();
        
        try {
            // 1. 登录获取token
            System.out.println("1️⃣ 登录获取认证token...");
            String token = login();
            if (token == null) {
                System.out.println("❌ 登录失败，无法获取token");
                return;
            }
            System.out.println("   ✅ Token获取成功: " + token.substring(0, 20) + "...");
            System.out.println();
            
            // 2. 添加主要定时任务
            System.out.println("2️⃣ 添加TooBit API交易对获取任务(白名单方案A)...");
            boolean task1Success = addScheduledTask(token, 
                "获取现货交易对",
                "SYSTEM",
                "spotCurrencyPairSyncTask.syncSpotCurrencyPairs()",
                "0 */5 * * * ?",
                "每5分钟同步 TooBit 现货交易对(symbolName优先)",
                "0"  // 启用状态
            );
            
            if (task1Success) {
                System.out.println("   ✅ 主要任务添加成功");
            } else {
                System.out.println("   ❌ 主要任务添加失败");
            }
            System.out.println();
            
            // 3. 添加完整验签任务
            System.out.println("3️⃣ 添加TooBit API完整验签任务...");
            boolean task2Success = addScheduledTask(token,
                "TooBit API完整验签测试",
                "SYSTEM", 
                "tooBitApiTask.getExchangeInfoWithFullSignature()",
                "0 */5 * * * ?",
                "每5分钟执行一次HMAC SHA256完整验签的exchangeInfo请求",
                "1"  // 暂停状态
            );
            
            if (task2Success) {
                System.out.println("   ✅ 完整验签任务添加成功");
            } else {
                System.out.println("   ❌ 完整验签任务添加失败");
            }
            System.out.println();
            
            // 4. 添加统计任务
            System.out.println("4️⃣ 添加TooBit API统计任务...");
            boolean task3Success = addScheduledTask(token,
                "TooBit API执行统计",
                "SYSTEM",
                "tooBitApiTask.getExecutionStatistics()",
                "0 */30 * * * ?", 
                "每30分钟输出TooBit API任务的执行统计信息",
                "1"  // 暂停状态
            );
            
            if (task3Success) {
                System.out.println("   ✅ 统计任务添加成功");
            } else {
                System.out.println("   ❌ 统计任务添加失败");
            }
            System.out.println();
            
            // 5. 获取任务列表验证
            System.out.println("5️⃣ 验证任务列表...");
            getJobList(token);
            
            System.out.println("🎉 === TooBit定时任务添加完成 ===");
            System.out.println();
            System.out.println("📋 访问方式:");
            System.out.println("   🌐 前端管理: http://localhost:1024/#/monitor/job");
            System.out.println("   🔑 登录账号: admin / admin123");
            
        } catch (Exception e) {
            System.out.println("🚨 执行异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 登录获取token
     */
    private static String login() throws Exception {
        URL url = new URL(BASE_URL + "/login");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        
        String loginData = "{\"username\":\"admin\",\"password\":\"admin123\",\"code\":\"\",\"uuid\":\"\"}";
        
        try (OutputStream os = conn.getOutputStream()) {
            os.write(loginData.getBytes("UTF-8"));
        }
        
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            String response = readResponse(conn);
            // 简单解析token
            int tokenStart = response.indexOf("\"token\":\"") + 9;
            if (tokenStart > 8) {
                int tokenEnd = response.indexOf("\"", tokenStart);
                return response.substring(tokenStart, tokenEnd);
            }
        }
        
        return null;
    }
    
    /**
     * 添加定时任务
     */
    private static boolean addScheduledTask(String token, String jobName, String jobGroup, 
                                          String invokeTarget, String cronExpression, 
                                          String remark, String status) throws Exception {
        URL url = new URL(BASE_URL + "/monitor/job");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + token);
        conn.setDoOutput(true);
        
        String jobData = String.format(
            "{\"jobName\":\"%s\",\"jobGroup\":\"%s\",\"invokeTarget\":\"%s\"," +
            "\"cronExpression\":\"%s\",\"misfirePolicy\":\"2\",\"concurrent\":\"1\"," +
            "\"status\":\"%s\",\"remark\":\"%s\"}",
            jobName, jobGroup, invokeTarget, cronExpression, status, remark
        );
        
        try (OutputStream os = conn.getOutputStream()) {
            os.write(jobData.getBytes("UTF-8"));
        }
        
        int responseCode = conn.getResponseCode();
        String response = readResponse(conn);
        
        System.out.println("     响应码: " + responseCode);
        System.out.println("     响应: " + (response.length() > 100 ? response.substring(0, 100) + "..." : response));
        
        return responseCode == 200 && response.contains("\"code\":200");
    }
    
    /**
     * 获取任务列表
     */
    private static void getJobList(String token) throws Exception {
        URL url = new URL(BASE_URL + "/monitor/job/list?pageNum=1&pageSize=20");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer " + token);
        
        int responseCode = conn.getResponseCode();
        String response = readResponse(conn);
        
        if (responseCode == 200 && response.contains("TooBit")) {
            int tooBitCount = countOccurrences(response, "TooBit");
            System.out.println("   ✅ 任务列表获取成功，发现 " + tooBitCount + " 个TooBit相关任务");
        } else {
            System.out.println("   ❌ 任务列表获取失败，响应码: " + responseCode);
        }
    }
    
    /**
     * 读取HTTP响应
     */
    private static String readResponse(HttpURLConnection conn) throws Exception {
        InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
        if (is == null) return "";
        
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }
    
    /**
     * 计算字符串出现次数
     */
    private static int countOccurrences(String text, String pattern) {
        if (text == null || pattern == null) return 0;
        int count = 0, index = 0;
        while ((index = text.indexOf(pattern, index)) != -1) {
            count++;
            index += pattern.length();
        }
        return count;
    }
}